<template>
	<div class="prescription-search-page search-page-box">
		<div class="search-cont">
			<BreadCrumb :data="dataObj.crumbList" />
			
			<div class="crose-ui-pie" v-if="router.currentRoute.value.query.origin == 'header'">
				<div class="echart-item">
					<uiEchart :config="optionChartType" id="chartType" :vt="dataObj.echartoptVt1" @clk="clkTypeChart" ref="chartType"/>
				</div>
				<div class="echart-item">
					<uiEchart :config="optionChartDose" id="chartDose" :vt="dataObj.echartoptVt1" @clk="clkDoseChart" ref="chartDose"/>
				</div>
			</div>

			<div class="total-box" v-if="dataObj.queryTy == 1">
				<div class="total-wrap">
					<div class="tatal-cont">
						<div class="locate-box">
							<el-image class="search-img" :src="searchImg" fit="contain" />
						</div>
						<div class="tatal-txt" v-lang="{lang: controlSto.language, lgid: -18}">Prescription</div>
						<div class="tatal-txt" v-lang="{lang: controlSto.language, lgid: -42}">Total</div>
						<div class="tatal-txt">:</div>
						<div class="tatal-txt">
							{{dataObj.searchReaultTotal}}
						</div>
					</div>
					<div class="more-box">
						<div class="more-wrap" @click.stop="toMore">
							<div class="more-txt" v-lang="{lang: controlSto.language, lgid: -43}">More</div>
							<div class="more-img-box">
								<el-image class="more-img" :src="moreImg" fit="contain" />
							</div>
						</div>
					</div>
				</div>
			</div>

			<div class="condition-box">
				<div class="condition-left">
					<SearchDrop class="cond-item">
						<template #title>
							<!-- <span v-lang="{lang: controlSto.language, lgid: 7, list: controlSto.langList}"></span> -->
							<span v-lang="{lang: controlSto.language, lgid: -44}">List sort</span>
						</template>
						<template #dropcont>
							<div class="cond-drop-cont-wrap">
								<el-radio-group v-model="condObj.sort" @change="toSearch()">
									<div class="cond-radio-wrap">
										<el-radio class="cond-radio-item" value="Asc"><span v-lang="{lang: controlSto.language, lgid: -49}"></span></el-radio>
										<el-radio class="cond-radio-item" value="Desc"><span v-lang="{lang: controlSto.language, lgid: -50}"></span></el-radio>
									</div>
								</el-radio-group>
						</div>
						</template>
					</SearchDrop>

					<SearchDrop class="cond-item">
						<template #title>
							<span v-lang="{lang: controlSto.language, lgid: -45}">Type</span>
							<!-- <el-popover placement="top-start">
								<el-checkbox class="all-choose-cls"
									v-model="condObj.TypeAll"
									@change="allChooseType"
								>
								<span @click.stop="condObj.TypeAll = !condObj.TypeAll" v-lang="{lang: controlSto.language, lgid: -130}">select all</span>
							</el-checkbox>
								<template #reference>
									<span v-lang="{lang: controlSto.language, lgid: -45}">Type</span>
								</template>
							</el-popover> -->
						</template>
						<template #dropcont>
							<div class="cond-drop-cont-wrap">
								<el-checkbox class="all-choose-cls"
										v-model="condObj.TypeAll"
										@change="allChooseType"
									>
									<span @click.stop="condObj.TypeAll = !condObj.TypeAll" v-lang="{lang: controlSto.language, lgid: -130}">select all</span>
								</el-checkbox>
								<el-checkbox-group v-model="condObj.typeList" @change="toSearch()">
									<div class="cond-chbox-wrap">
										<el-checkbox class="cond-chbox-item" v-for="item in dataObj.typeList" :key="'ty_' + item.typeCode" :value="item.typeCode" :label="item.typeName"  />
									</div>
								</el-checkbox-group>
							</div>
						</template>
					</SearchDrop>

					<SearchDrop class="cond-item">
						<template #title>
							<span v-lang="{lang: controlSto.language, lgid: -69}">Dosage form</span>
							<!-- <el-popover placement="top-start">
								<el-checkbox class="all-choose-cls"
									v-model="condObj.dosaAll"
									@change="allChooseDosa"
								>
								<span @click.stop="condObj.dosaAll = !condObj.dosaAll" v-lang="{lang: controlSto.language, lgid: -130}">select all</span>
							</el-checkbox>
								<template #reference>
									<span v-lang="{lang: controlSto.language, lgid: -69}">Dosage form</span>
								</template>
							</el-popover> -->
						</template>
						<template #dropcont>
							<div class="cond-drop-cont-wrap">
								<el-checkbox class="all-choose-cls"
									v-model="condObj.dosaAll"
									@change="allChooseDosa"
								>
									<span @click.stop="condObj.dosaAll = !condObj.dosaAll" v-lang="{lang: controlSto.language, lgid: -130}">select all</span>
								</el-checkbox>
								<el-checkbox-group v-model="condObj.dosageList" @change="toSearch()">
									<div class="cond-chbox-wrap">
										<el-checkbox class="cond-chbox-item" v-for="item in dataObj.dosageList" :key="'prop_' + item.id" :value="item.dosageFormCode" :label="item.dosageFormName"  />
									</div>
								</el-checkbox-group>
							</div>
						</template>
					</SearchDrop>
				</div>
				<div class="condition-right">
					<div class="ipt-cont">
						 <el-input class="ipt-search prescription-cond-ipt" clearable="true" v-model="condObj.searchword" autofocus :placeholder="searchPlace" />
						 <el-tag class="tags-search" v-if="condObj.wordpreposition" closable @close="handleClose(tag)" round type="warning">
								<span class="tag-box">{{ condObj.wordpreposition }}</span>
							</el-tag>
					</div>
					<SearchBtn class="search-item" @click.stop="toSearch()"/>
					<TableFilter class="search-item" :column="dataObj.columnList" :filterKey="condObj.filterKey" @onChg="chgTableCol"/>

					<SearchLoad :type="downloadCode" :uiCode="condObj.uiCode"
						:para="{
							'langCode': controlSto.language == 1 ? 'ENG' : 'CHN',
							'content': condObj.searchword,
							'uiTypeCode': condObj.uiCode,
							'prescriptionType': condObj.typeList.join(',') || '',
							'dosageForm': condObj.dosageList.join(',') || '',
							'sortType': condObj.sort,
							'prepositionContent': condObj.wordpreposition
						}"
						/>
				</div>
			</div>
			<div class="cont-box">
				<uiTable
						:config="dataObj.tableConfig"
						:columnConfig="dataObj.columnConfig" 
						:data="dataObj.dataList"
						:loading="isLoading"
						:key="dataObj.searchTablevt">
						<template #[condObj.idField]="{ row }">
							<div class="jump-box" @click.stop="toClkItem(row)"><span>{{row[condObj.idField]}}</span></div>
						</template>
						<template #[condObj.nameField]="{ row }">
							<div class="jump-box" @click.stop="toClkItem(row)"><span>{{row[condObj.nameField]}}</span></div>
						</template>
                </uiTable>

				<div class="page-box" v-if="condObj.total > 10">
					<uiPagination
						:total="condObj.total" :pageSize="condObj.pageSize" :pageIndex="condObj.pageIndex"
						@onSizeChange="chgSize" @onCurrentChange="chgCurrnt"/>
				</div>
			</div>

		</div>
    </div>
</template>



<script setup>
    import { ref, reactive, computed, onBeforeMount, watch, nextTick } from 'vue'
    import BreadCrumb from '@/components/BreadCrumb.vue'
    import SearchBtn from '@/components/SearchBtn.vue'
    import TableFilter from '@/components/TableFilter.vue'
    import uiTable from '@/components/ui-table.vue'
    import SearchLoad from '@/components/SearchLoad.vue'
    import SearchDrop from '@/components/SearchDrop.vue'
    import uiPagination from '@/components/ui-pagination.vue'
		import uiEchart from '@/components/ui-echart.vue'

		import { debounce } from 'lodash'
		import { useRouter } from 'vue-router'
		import { controlStore } from '@/stores/control'
		import { langTxt, getFilterThArr, getFilterLangArr, computedgraphOptions } from '@/utils/util'

		import { 
			getTableThList,
			getPrescriptionList,
			getPresTypeList,
			getPresDosageFormList,
			getPrescriptionSearchList,
			prescriptionHomeStatistic,
			getsearchPrescrTotal
		} from '@/service/tcm'


    import searchImg from '@/assets/img/searchgrey.png'
    import moreImg from '@/assets/img/more-arrow.png'

	let searchDebounce = null;
		let totalresult = null;
	const controlSto = controlStore();
	const router = useRouter();
  const isLoading = ref(true);
	const downloadCode = ref('prescription');
	let typeStatisList = reactive([])
	let dosageStatisList = reactive([])
	const chartType = ref(null);
	const chartDose = ref(null);
	const condObj = reactive({ // list sort type  dosage form
		idField: '100716826576557301',
		nameField: '100716826576557302',
		searchword: '',
		filterKey: 'prescription',
        uiCode: 'prescription',
		sort: 'Asc',
		typeList: [],
		dosageList: [],
		word: '',
		sortType:  'Asc',
		typeStr: '',
		dosageStr: '',
		total: 0,
		pageSize: 10,
		pageIndex: 1,
		dosaAll: true,
		TypeAll: true
	});
	const dataObj = reactive({
		queryTy: 0,
		searchReaultTotal: 0,
		crumbList: [
            {
				fkey: '-16',
                lable: 'Home',
                name: 'home'
            }, {
				fkey: '-18',
                lable: 'Prescription',
                name: 'pressearch'
            }
        ],
		// searchType: 1,
		typeList: [],
		dosageList: [],
		searchTablevt: 1,
		columnList: [],
		tableConfig: {
			// size: 'small',
			'tooltip-effect': 'dark',
			'highlight-current-row': true,
			stripe: true,
			'header-cell-style': { background: '#BC9F77', color: '#FFF' },
		},
		
		columnConfig: [],
		dataList: [],
	});
	let optionChart = reactive({
		typeList: [],
		doseList: []
	})
let optionChartType = computedgraphOptions(langTxt(controlSto.language, '-99'), langTxt(controlSto.language, '-108'), optionChart.typeList, true, 'center')
let optionChartDose = computedgraphOptions(langTxt(controlSto.language, '-100'), langTxt(controlSto.language, '-107'), optionChart.doseList, true, 'center', '55%')
const clkTypeChart = (item) => {
	condObj.typeList = [item.data.typeCode]
	toSearch()
}
const clkDoseChart = (item) => {
	condObj.dosageList = [item.data.dosageFormCode]
	toSearch()
}
	const searchPlace = computed(() => {
		return langTxt(controlSto.language, '-15');
	});
	onBeforeMount(()=> {
		initPage();
	});

	const initPage = () => {
		initQuery();
		initCond();
		getTableTh();
	};

	const reSwitch = () => {	
		optionChart.doseList = []
		optionChart.typeList = []
		initCond();
    // toGetData();
	};

	const initCond = () => {
		if (router.currentRoute.value.query.t) downloadCode.value = 'prescriptionSearch'
		else {
			downloadCode.value = 'prescription';
			
		}
		// toGetDosageList();
		// toGetTypeList();
		getData();
		// if(!router.currentRoute.value.query.t)toGetPrescriptionHomeStatistic();
	};
	
	const initDebounce = (type) => {
				// totalresult = debounce(() => {
				// 	if (router.currentRoute.value.query.t) togetsearchPrescrTotal();
				// }, 1000)
        // searchDebounce = debounce((e) => {
				// 	if (router.currentRoute.value.query.t) {
				// 		getDataSearchList()
				// 	} else {
				// 		getDataList();
				// 	}
        // }, 1000);
    };

	const initQuery = () => {
		if(router.currentRoute.value.query && router.currentRoute.value.query.t && router.currentRoute.value.query.t == 1) {
			dataObj.queryTy = 1;
			dataObj.crumbList = [
				{
					fkey: '-16',
					lable: 'Home',
					name: 'home'
				}, {
					fkey: '-14',
					lable: 'search',
					name: 'search'
				}
			];
			if(router.currentRoute.value.query.wk) {
				// condObj.searchword = router.currentRoute.value.query.wk || '';
				condObj.wordpreposition = router.currentRoute.value.query.wk || '';
			} else {
				condObj.searchword = '';
			}
		} else {
			dataObj.queryTy = 0;
			dataObj.crumbList = [
				{
					fkey: '-16',
					lable: 'Home',
					name: 'home'
				}, {
					fkey: '-18',
					lable: 'Prescription',
					name: 'pressearch'
				}
			];
			condObj.searchword = '';
		}
    };

	const handleClose = () => {
		condObj.wordpreposition = '';
		togetsearchPrescrTotal();
		getDataSearchList();
	}
	const allChooseDosa = () => {
		if(condObj.dosageList.length == dataObj.dosageList.length) {
			condObj.dosageList = [];
		} else {
			condObj.dosageList = [];
			dataObj.dosageList.forEach(e => {
				condObj.dosageList.push(e.dosageFormCode)
			})
		}
		toSearch();
	}
	const allChooseType = () => {
		if(condObj.typeList.length == dataObj.typeList.length) {
			condObj.typeList = [];
		} else {
			condObj.typeList = [];
			dataObj.typeList.forEach(e => {
				condObj.typeList.push(e.typeCode)
			})
		}
		toSearch();
	}
	const toGetPrescriptionHomeStatistic = () => {
		const params = {
			langCode: controlSto.language == 1 ? 'ENG' : 'CHN',
			uiTypeCode: condObj.uiCode,
			content: condObj.searchword,
			// dosageForm: condObj.dosageStr || '',
			// prescriptionType: condObj.typeStr || ''
		}
		prescriptionHomeStatistic(params).then(res => {
			if (res.success) {
				let dosageStatisObj = res.data.dosageFormStatistics;
				let typeStatisObj = res.data.typeStatistics;
				optionChart.doseList = [];
				optionChart.typeList = [];
				for (let k in dosageStatisObj) {
					if(Number(dosageStatisObj[k]) > 0) {
						dataObj.dosageList.forEach((item, index) => {
							if(item.dosageFormCode == k) {
								optionChart.doseList.push({dosageFormCode: k, value: dosageStatisObj[k], name: item.dosageFormName})
							}
						})
					}
				}
				optionChartDose.series[0].data = optionChart.doseList;
				optionChartDose.title.text = langTxt(controlSto.language, '-100');
				optionChartDose.title.subtext = langTxt(controlSto.language, '-108');
				optionChartDose.toolbox.feature.saveAsImage.title = controlSto.language == 1 ? 'Download' : '下载';
				optionChart.doseList.length < 5 ? optionChartDose.legend.top = 'center' : ''
				chartDose.value.initEchart()
				for (let key in typeStatisObj) {
					dataObj.typeList.forEach(e => {
						if (e.typeCode == key) {
							optionChart.typeList.push({typeCode: key, value: typeStatisObj[key], name: e.typeName})
						}
					})
				}
				optionChartType.series[0].data = optionChart.typeList;
				optionChartType.title.text = langTxt(controlSto.language, '-99');
				optionChartType.title.subtext = langTxt(controlSto.language, '-108');
				optionChartType.toolbox.feature.saveAsImage.title = controlSto.language == 1 ? 'Download' : '下载';
				optionChart.typeList.length < 5 ? optionChartType.legend.top = 'center' : ''
				chartType.value.initEchart()
				
			}
		}).catch(() => {});
	}
	
	const getData = () => {
		condObj.typeList = []
		condObj.dosageList = [];
		const param = {langCode: controlSto.language == 1 ? 'ENG' : 'CHN',}
		Promise.all([getPresTypeList(param), getPresDosageFormList(param)]).then(res => {
			if (res[0].success) {
				res[0].data.forEach(e => {
					condObj.typeList.push(e.typeCode)
				})
				condObj.TypeAll = true;
				dataObj.typeList = res[0].data || [];
			}
			if (res[1].success && res[1].data) {
				res[1].data.forEach(e => {
					condObj.dosageList.push(e.dosageFormCode)
				})
				condObj.dosaAll = true;
					dataObj.dosageList = res[1].data || [];
					
			}
			if(router.currentRoute.value.query.t) {
				getDataSearchList();
				togetsearchPrescrTotal();
			} else {
				getDataList();
				toGetPrescriptionHomeStatistic();
			}
		})
	}
	const getDataSearchList = () => {
		isLoading.value = true;
		getPrescriptionSearchList({
			langCode: controlSto.language == 1 ? 'ENG' : 'CHN',
			content: condObj.searchword,
      uiTypeCode: condObj.uiCode,
			sortType: condObj.sortType,
			prescriptionType: condObj.typeList.join(',') || '',
			dosageForm: condObj.dosageList.join(',') || '',
			pageNo: condObj.pageIndex || 10,
			pageSize: condObj.pageSize || 1,
			prepositionContent: condObj.wordpreposition || '' //从首页带过来的搜索条件
		}).then(res => {
			isLoading.value = false;
			if (res.success && res.data && res.data.records) {
					dataObj.dataList = res.data.records || [];
					condObj.total = res.data.totalCount || 0;
			}
		}).catch(() => {
				isLoading.value = false;
		});
	}
	const getTableTh = () => {
        let params = {
            uiCode: condObj.filterKey,
            langCode: 'ENG,CHN'
        };

		getTableThList(params).then((res) => {
            isLoading.value = true;
            if (res.success) {
                let arr = res.data || [];
                let thArr = getFilterThArr(arr, condObj.filterKey);
								let langArr = getFilterLangArr(thArr);
								controlSto.setLangList(langArr);
								dataObj.columnList = thArr;
            }
        }).catch(() => {
            isLoading.value = false;
        });
    };

	
	const chgTableCol = (e) => {
		dataObj.columnConfig = e || [];
		dataObj.searchTablevt = new Date().valueOf();
    };

	const toGetData = () => {
        // searchDebounce && searchDebounce();
				if(router.currentRoute.value.query.t) {
				getDataSearchList();
				// togetsearchPrescrTotal();
			} else {
				getDataList();
				// toGetPrescriptionHomeStatistic();
			}
    };

	const getDataList = () => {
		let params = {
      langCode: controlSto.language == 1 ? 'ENG' : 'CHN',
			content: condObj.searchword,
      uiTypeCode: condObj.uiCode,
			sortType: condObj.sortType,
			prescriptionType: condObj.typeList.join(',') || '',
			dosageForm: condObj.dosageList.join(',') || '',
			pageNo: condObj.pageIndex || 10,
			pageSize: condObj.pageSize || 1,
			// prepositionContent: condObj.wordpreposition //从首页带过来的搜索条件
		}
        isLoading.value = true;
		getPrescriptionList(params).then((res) => {
            isLoading.value = false;
            if (res.success && res.data && res.data.records) {
                dataObj.dataList = res.data.records || [];
                condObj.total = res.data.totalCount || 0;
            }
        }).catch(() => {
            isLoading.value = false;
        });
    };

	const chgSize = (e) => {
        condObj.pageSize = e || 10;
        toGetData();
    };
    const chgCurrnt = (e) => {
        condObj.pageIndex = e || 1;
        toGetData();
    };

	const toSearch = () => {
        condObj.sortType = condObj.sort;
        // condObj.typeStr = condObj.typeList.join(',');
        // condObj.dosageStr = condObj.dosageList.join(',');
        condObj.pageIndex = 1;
        toGetData();
    };
const togetsearchPrescrTotal = () => {
	getsearchPrescrTotal({
		langCode: controlSto.language == 1 ? 'ENG' : 'CHN',
		uiTypeCode: condObj.uiCode,
		prepositionContent: condObj.wordpreposition || '',
		dosageForm: condObj.dosageList.join(',') || '',
		prescriptionType: condObj.typeList.join(',') || ''
	}).then(res => {
		if(res.success && res.data) {
			dataObj.searchReaultTotal = res.data.prescriptions || 0;
		}
	})
}
	
	const toMore = () => {
        router.push({ name: 'pressearch', query: { origin: 'header' } });
				condObj.wordpreposition = '';
    };

	const toClkItem = (rowItem) => {
        // router.push({ name: 'presdetail', query: {ty: dataObj.searchType}});
        router.push({ name: 'presdetail' , query: {id: rowItem[condObj.idField]} });
    };

	watch(() => router.currentRoute.value.name, (nv, ov) => {
		if(nv != ov) {
      initQuery();
		}
	});
	watch(() => [controlSto.language, router.currentRoute.value.wk], (nv, ov) => {
		if(nv != ov) {
			reSwitch();
			condObj.TypeAll = true;
			condObj.dosaAll = true;
		}
	}, {deep: true});
	watch(() => [condObj.typeList, condObj.dosageList], (n, v) => {
		// if(n != v) toSearch();
		if(n[0].length && n[0].length == dataObj.typeList.length) condObj.TypeAll = true;
		else condObj.TypeAll = false;

		if(n[1].length && n[1].length == dataObj.dosageList.length) condObj.dosaAll = true;
		else condObj.dosaAll = false;
	})
   
</script>

<style lang="scss" scoped>
	.prescription-search-page {
		height: 100%;
		min-height: calc(100vh - 250px);
		text-align: center;
		background-size: 100% 100%;
		position: relative;
		margin-bottom: 32px;
		.search-cont {
			display: inline-block;
			width: 100%;
    	text-align: left;
			.crose-ui-pie {
				display: flex;
				justify-content: space-around;
				padding: 0 0 12px;
				.echart-item {
					height: 240px;
					width: 33%;
					padding: 8px 24px 0;
					&:last-child {
						margin-left: 32px;
					}
				}
			}
			.total-box {
				padding: 8px 0 32px;
				.total-wrap {
					display: flex;
					height: 50px;
					padding: 0 24px;
					justify-content: space-between;
					line-height: 50px;
					background-color: #F5F7FA;
					.tatal-cont {
						font-size: 16px;
						.locate-box {
							position: relative;
							display: inline-block;
							top: 2px;
							padding-right: 10px;
							.search-img {
								height: 16px;
							}
						}
						.tatal-txt {
							display: inline-block;
							padding-right: 4px;
							.tags-search {
								margin-left: 30px;
							}
							.tag-box {
								max-width: 100px;
								white-space: nowrap;
								overflow: hidden;
								text-overflow: ellipsis;
							}
						}
					}
					.more-box {
						.more-wrap {
							cursor: pointer;
							.more-txt {
								display: inline-block;
								font-size: 16px;
								font-weight: 600;
								color: #967846;
							}
							.more-img-box {
								position: relative;
								display: inline-block;
								top: 3px;
								.more-img {
									height: 16px;
								}
							}
						}
					}
				}
			}

			.condition-box {
				display: flex;
				padding-bottom: 38px;
				justify-content: space-between;
				// border: 1px solid red;
				.condition-left {
					.cond-item {
						margin-right: 16px;
					}
				}
				.condition-right {
					.ipt-cont {
						display: inline-block;
						padding-right: 16px;
						position: relative;
						.tags-search {
							position: absolute;
							left: 0;
							top: 36px;
							max-width: 150px;
						}
						.ipt-search {
							// width: 300px;
						}
					}
					.search-item {
						margin-right: 16px;
					}
				}
			}
			.cont-box {
				.jump-box {
					font-weight: 400;
					font-size: 14px;
					color: #1677FF;
					cursor: pointer;
				}
			}



		}
	}
	
</style>


<style lang="scss">
    .cond-item-drop-box {
        .cond-drop-cont-wrap {
			max-height: 260px;
			overflow-y: auto;
			.cond-chbox-wrap {
				width: 200px;
				padding: 0;
				.cond-chbox-item {
					width: 188px;
					padding-left: 12px;
					margin-right: 0;
				}
				// :deep() {
				// 	.el-checkbox__input.is-checked .el-checkbox__inner {
				// 		background-color: #BC9F77;
				// 		border-color: #BC9F77;
				// 	}
				// }

				.el-checkbox__inner:hover {
					border-color: #BC9F77;
				}
				.el-checkbox__input.is-checked .el-checkbox__inner {
					background-color: #BC9F77;
					border-color: #BC9F77;
				}
				.el-checkbox__input.is-checked + .el-checkbox__label {
					color: #BC9F77;
				}
			}

			.cond-radio-wrap {
				width: 200px;
				padding: 0;
				.cond-radio-item {
					width: 188px;
					padding-left: 12px;
					margin-right: 0;
				}
				.el-radio__inner:hover {
					border-color: #BC9F77;
				}
				.el-radio__input.is-checked .el-radio__inner {
					background-color: #BC9F77;
					border-color: #BC9F77;
				}
				.el-radio__input.is-checked + .el-radio__label {
					color: #BC9F77;
				}
			}
        }
    }
</style>